package mspbots.data.tl.prod.timedoctor.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultMessageModel;
import mspbots.data.tl.prod.other.mapper.SysUserMappingMapper;
import mspbots.data.tl.prod.other.model.SysUserMapping;
import mspbots.data.tl.prod.timedoctor.mapper.TimedoctorUserMapper;
import mspbots.data.tl.prod.timedoctor.mapper.TimedoctorWorklogsMapper;
import mspbots.data.tl.prod.timedoctor.model.AttendanceTimedoctorWorklogs;
import mspbots.data.tl.prod.timedoctor.model.TimedoctorUser;
import mspbots.data.tl.prod.timedoctor.service.TimedoctorWorklogsService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

/**
 * @author Jay.Yang
 */

@Service
@Log4j2
@RequiredArgsConstructor
@DS("master")
public class TimedoctorWorklogsServiceImpl extends AbstractBaseServiceImpl<TimedoctorWorklogsMapper, AttendanceTimedoctorWorklogs>
        implements TimedoctorWorklogsService {

    private final SysUserMappingMapper userMappingMapper;
    private final TimedoctorUserMapper timedoctorUserMapper;

    @Override
    public void sync(ResultMessageModel model) {

        if (!ObjectUtils.isEmpty(model.getEntity()) && !"[[]]".equals(model.getEntity().toString())
                && ResultMessageModel.MessageModelAction.ADD.equals(model.getAction())) {

            List<AttendanceTimedoctorWorklogs> worklogsList = new ArrayList<>();
            Iterator<JsonNode> nodes = model.getEntity().get(0).elements();
            while (nodes.hasNext()) {
                JsonNode node = nodes.next();
                LocalDateTime start = !StringUtils.isEmpty(node.get("start")) ?
                        LocalDateTime.parse(node.get("start").asText(), DateTimeFormatter.ISO_DATE_TIME) : null;
                AttendanceTimedoctorWorklogs data = AttendanceTimedoctorWorklogs.builder()
                        .startTime(start)
                        .endTime(ObjectUtils.isEmpty(start) ? null : start.plusMinutes(node.get("time").asLong() / 60))
                        .duration(node.get("time").asLong() / 60)
                        .timedoctorUserId(node.get("userId").asText())
                        .syncTime(LocalDateTime.now())
                        .build();
                data.setTenantCode(model.getTenantId());
                worklogsList.add(data);
            }
            String timedoctorUserId = worklogsList.get(0).getTimedoctorUserId();
            //select sys_user_mapping by timedoctor.userId, get sys_user_mapping.userId
            SysUserMapping userMapping = userMappingMapper.selectOne(Wrappers.<SysUserMapping>lambdaQuery()
                    .eq(SysUserMapping::getTenantCode, model.getTenantId())
                    .eq(SysUserMapping::getMappingUserId, timedoctorUserId)
                    .eq(SysUserMapping::getUserType, "4")
                    .last("limit 1"));

            TimedoctorUser timedoctorUser = timedoctorUserMapper.selectOne(Wrappers.<TimedoctorUser>lambdaQuery()
                    .eq(TimedoctorUser::getTenantCode, model.getTenantId())
                    .eq(TimedoctorUser::getUserId, timedoctorUserId)
                    .last("limit 1"));

            worklogsList.sort(Comparator.comparing(AttendanceTimedoctorWorklogs::getStartTime));
            for (AttendanceTimedoctorWorklogs data : worklogsList) {
                data.setSysUserId(ObjectUtils.isEmpty(userMapping) ? null : userMapping.getUserId());
                data.setTimedoctorUserName(ObjectUtils.isEmpty(timedoctorUser) ? null : timedoctorUser.getName());

                AttendanceTimedoctorWorklogs dbData = super.baseMapper.selectOne(Wrappers.<AttendanceTimedoctorWorklogs>lambdaQuery()
                        .eq(AttendanceTimedoctorWorklogs::getTenantCode, model.getTenantId())
                        .eq(AttendanceTimedoctorWorklogs::getTimedoctorUserId, timedoctorUserId)
                        .eq(AttendanceTimedoctorWorklogs::getStartTime, data.getStartTime())
                        .last("limit 1"));

                if (ObjectUtils.isEmpty(dbData)) {
                    super.baseMapper.insert(data);
                } else {
                    data.setId(dbData.getId());
                    super.baseMapper.updateById(data);
                }
            }
        }
    }
}
